//
//  SearchResultViewController.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2023/10/12.
//

import UIKit
import MJRefresh
import SkeletonView
class SearchResultViewController: BaseViewController {
    var searchText = ""
    var searchTextField: UITextField!
    var emptyView: LYEmptyView!
    //var subfieldView: SubfieldTopView!
    var filtrateView: FiltrateUserCarView!
    var collectionView: UICollectionView!
    var selectParam = SelectparameterModel()  //选中的参数
    var pageNo: NSInteger = 1
    var dataArr = NSMutableArray()
    var goTopBtn: UIButton = {
        let tempBtn = UIButton()
        tempBtn.setup_image(image: UIImage.init(named: "icon_suspend"))
        tempBtn.isHidden = true
        return tempBtn
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navBar.wr_setBottomLineHidden(hidden: true)
        self.initSearchView()
        //self.initSubfieldTopView()
        self.initFiltrateUserCarView()
        self.initCollectionView()
        
        self.view.addSubview(goTopBtn)
        self.addSnpLayout()
        self.view.layoutIfNeeded()
        self.collectionView.showAnimatedGradientSkeleton()
        self.fetchGetCarList(hud: false)
    }
    
    private func addSnpLayout(){
        self.goTopBtn.snp.makeConstraints { make in
            make.left.equalTo(12)
            make.bottom.equalTo(-TabbarHeight)
            make.width.equalTo(44)
            make.height.equalTo(44)
        }
    }
    
    func initSearchView() {
        
        let searchView = UIView(frame: CGRect(x: 54, y: NavBarHight - 39, width: kScreenWidth - 130, height: 32))
        searchView.backgroundColor = .white
        searchView.layer.cornerRadius = 16
        searchView.clipsToBounds = true
        searchView.layer.borderWidth = 1.5
        searchView.layer.borderColor = UIColor(hex: 0x222222).cgColor
        self.navBar.addSubview(searchView)
        
        let imageSearch = UIImageView(frame: CGRect(x: 13, y: 9, width: 14, height: 14))
        imageSearch.image = UIImage(named: "icon_search")
        searchView.addSubview(imageSearch)
        
        self.searchTextField = UITextField.init(frame: CGRect(x:imageSearch.right + 10, y: 0, width: searchView.width - 50, height: 32))
        self.searchTextField.textColor = Theme.titleLabColor
        self.searchTextField.font = UIFont.init(name: Theme.PingFangSCRegular, size: 14)
        self.searchTextField.placeholder = MMLocalizedString("search_vehicle", comment: "搜索车辆")
        self.searchTextField.returnKeyType = .search
        self.searchTextField.keyboardType = .default
        self.searchTextField.clearButtonMode = .always
        self.searchTextField.delegate = self
        self.searchTextField.addTarget(self , action: #selector(self.textFieldChanged(textField:)), for: UIControlEvents.editingChanged)
        self.searchTextField.text = self.searchText
        searchView.addSubview(self.searchTextField)
        
        let searchBtn = UIButton(frame: .zero)
        searchBtn.setTitle(MMLocalizedString("search", comment: "搜索"), for: .normal)
        searchBtn.setTitleColor(Theme.mainColor, for: .normal)
        searchBtn.addTarget(self, action: #selector(confirmSearchBtnAction), for: .touchUpInside)
        searchBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCMedium, size: 14)
        self.navBar.addSubview(searchBtn)
        
        searchBtn.snp.makeConstraints { make in
            make.right.equalTo(-14)
            make.height.width.equalTo(44)
            make.bottom.equalTo(0)
        }
        
    }
    
    //分栏
//    func initSubfieldTopView(){
//        self.subfieldView = SubfieldTopView(frame: CGRect(x: 0, y: NavBarHight + 4, width: kScreenWidth, height: 34))
//        self.subfieldView.delegate = self
//        self.view.addSubview(self.subfieldView)
//    }
    
    ///筛选
    func initFiltrateUserCarView(){
        self.filtrateView = FiltrateUserCarView(frame: CGRect(x: 0, y: NavBarHight + 8, width: kScreenWidth, height: 32))
        self.filtrateView.delegate = self
        self.view.addSubview(self.filtrateView)
        
    }
    
    func initCollectionView(){
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = 10
        layout.minimumLineSpacing = 10
        layout.scrollDirection = .vertical
        let ww = (kScreenWidth - 38)/2
        layout.itemSize = CGSize(width: ww, height: 210)
        layout.sectionInset = UIEdgeInsets(top: 0, left: 14, bottom: 0, right: 14)
        self.collectionView = UICollectionView(frame: CGRect(x: 0, y: self.filtrateView.frame.maxY + 8, width: kScreenWidth, height: kScreenHeight - self.filtrateView.frame.maxY - 8 - IphoneXMarginBottom), collectionViewLayout: layout)
        self.collectionView.delegate = self
        self.collectionView.dataSource = self
        self.collectionView.register(GoodsCollectionViewCell.self, forCellWithReuseIdentifier: "GoodsCollectionViewCell")
        self.collectionView.register(SkeletonCollectionCell.self, forCellWithReuseIdentifier: "SkeletonCollectionCell")
        self.collectionView.backgroundColor = .white
        self.view.addSubview(self.collectionView)
        self.collectionView.keyboardDismissMode = .onDrag
        self.collectionView.showsVerticalScrollIndicator = false
        self.collectionView.isSkeletonable = true
        self.setUpNoData()
        self.addPullRefreash()
        self.addLoadMoreRefreash()
    }
    
    //MARK: - 下拉刷新
    private func addPullRefreash()  {
        self.collectionView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: { [weak self] in
            self?.pageNo = 1
            self?.fetchGetCarList(hud: false)
        })
    }
    
    //MARK: - 上拉加载更多
    private func addLoadMoreRefreash()  {
        self.collectionView.mj_footer = ExtNoMoreRefreashFooterView.init(refreshingBlock: { [weak self] in
            self?.pageNo += 1
            self?.collectionView.mj_footer.endRefreshing()
        })
    }
    
    
    ///空视图
    func setUpNoData() {
        self.emptyView = LYEmptyView.emptyActionView(withImageStr: "icon_search_empty", titleStr: MMLocalizedString("no_matching_vehicle_yet", comment: "很抱歉，暂时没找到符合条件的车辆"), detailStr: "", btnTitleStr: "") {
            
        }
        emptyView?.subViewMargin = 28;
        emptyView?.contentViewOffset = -100
        emptyView?.isHidden = true
        self.collectionView.ly_emptyView = self.emptyView
    }
    
    /**
     "mileageMax":  最大量程数,初始化页面不传
     "mileageMin": 最小量程数,初始化页面不传
     "seatnumMax": 最大座位数,初始化页面不传
     "seatnumMin": 最小座位数,初始化页面不传
     "yearMax": 最大年限,初始化页面不传
     "yearMin": 最小年限,初始化页面不传
     "priceMax": 最贵,初始化页面不传
     "priceMin": 最便宜,初始化页面不传
     "storeId": 门店ID,初始化页面不传 
     */
    func fetchGetCarList(hud: Bool){
        if hud {
            //self.view.showLoadingHUDText(nil)
            self.collectionView.showAnimatedGradientSkeleton()
        }
        var param1: [String: String] = [:]
        
        if self.searchTextField.text != ""{
            param1["carName"] = self.searchTextField.text
        }
        
        if (self.selectParam.brandId ?? 0) > 0{
            param1["brandId"] = ("\(self.selectParam.brandId ?? 0)")
        }
        
        if (self.selectParam.seriesId ?? 0) > 0{
            param1["seriesId"] = ("\(self.selectParam.seriesId ?? 0)")
        }
        
        if (self.selectParam.mileageMax ?? 0) > 0 {
            param1["mileageMax"] = (self.selectParam.mileageMax ?? 0).cleanZero
        }
        if (self.selectParam.mileageMin ?? 0) > 0 {
            param1["mileageMin"] = (self.selectParam.mileageMin ?? 0).cleanZero
        }
        
        if (self.selectParam.seatnumMax ?? 0) > 0 {
            param1["seatnumMax"] = "\(self.selectParam.seatnumMax ?? 0)"
        }
        if (self.selectParam.seatnumMin ?? 0) > 0 {
            param1["seatnumMin"] = "\(self.selectParam.seatnumMin ?? 0)"
        }
        
        if (self.selectParam.yearMax ?? "") != "" {
            param1["yearMax"] = self.selectParam.yearMax ?? ""
        }
        if (self.selectParam.yearMin ?? "") != "" {
            param1["yearMin"] = self.selectParam.yearMin ?? ""
        }
        
        if self.selectParam.priceGroup != nil && (self.selectParam.priceMax ?? "") != "" {
            param1["priceMax"] = (self.selectParam.priceMax ?? "")
        }
        
        if self.selectParam.priceGroup != nil && (self.selectParam.priceMin ?? "") != "" {
            param1["priceMin"] = (self.selectParam.priceMin ?? "")
        }
        
        if (self.selectParam.carCategoryIds) != ""{
            param1["carCategoryIds"] = (self.selectParam.carCategoryIds)
        }
        
        if (self.selectParam.orderProperty) != "" {
            param1["orderProperty"] = self.selectParam.orderProperty
            
            if self.selectParam.ascOrDesc >= "0" {
                param1["ascOrDesc"] = self.selectParam.ascOrDesc
            }
        
        }
        
        param1["pageNumber"] = "\(self.pageNo)"
        param1["pageSize"] = "20"
        
   
        
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.userdCarPage(param: param1), objectType: UserCarModel.self) { data in
            self.view.handleLoading()
            self.collectionView.mj_header.endRefreshing()
            let resultObj = data as! UserCarModel
            
            if self.pageNo == 1 {
                self.dataArr.removeAllObjects()
            }
            if resultObj.code == "1" {
                //默认选择
                let temp = resultObj.data?.content ?? []
                self.dataArr.addObjects(from: temp)
            }else{
                self.view.makeToastBottom(message: resultObj.msg ?? "")
            }
            
            // 收藏或者取消收藏(可变数组获取model)
            self.dataArr.map{$0 as? VehicleLisetModel}.forEach({ item in
                item?.favoriteBlock = { [weak self] in
                    self?.requestFavorite(model: item!)
                }
            })
            self.collectionView.reloadData()
            if self.pageNo == 1 && self.dataArr.count > 0 {
                //展示
                self.filtrateView.isHidden = false
                self.collectionView.frame = CGRect(x: 0, y: self.filtrateView.frame.maxY + 8, width: kScreenWidth, height: kScreenHeight - NavBarHight - 86)
            }else{
                self.filtrateView.isHidden = true
                self.collectionView.frame = CGRect(x: 0, y: self.filtrateView.frame.maxY + 8, width: kScreenWidth, height: kScreenHeight - NavBarHight - 54)
            }
            self.willShowSketchView()
        } error: { err in
            self.willShowSketchView()
            self.view.handleLoading()
            self.collectionView.mj_header.endRefreshing()
            self.view.makeToastBottom(message: err?.domain ?? "")
        }
    }
    
    private func willShowSketchView(){
        if self.dataArr.count > 0  {
            self.emptyView.isHidden = true
        }else{
            self.emptyView.isHidden = false
        }
        self.collectionView.hideSkeleton()
    }
    
    //收藏取消收藏
    func requestFavorite(model: VehicleLisetModel){
        
        if UserModule.shared.isLogined == false{
            self.jumpToLogin()
            return
        }
        let param = ["usedcarId": "\(model.id ?? 0)"]
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.favorite(param: param),objectType: CommondResModel.self) { data in
            let resultObj = data as! CommondResModel
            if resultObj.code == "1" {
                if model.favorite == false{
                    self.view.makeToast(message: MMLocalizedString("successful_collection", comment: "收藏成功"))
                    model.favorite = true
                }else{
                    self.view.makeToast(message: MMLocalizedString("uncollected", comment: "已取消收藏"))
                    model.favorite = false
                }
                self.collectionView.reloadData()
            }else{
                self.view.makeToast(message: resultObj.msg ?? "")
            }
        }error: { err in
            self.view.makeToast(message: err?.domain ?? "")
        }
    }
    
    
    //MARK： - Aation
    @objc func textFieldChanged(textField: UITextField){
        printLog(textField.text)
        if textField.text == "" {
            //说明为空
        }else{
        }
    }
    
    ///确定搜索
    @objc func confirmSearchBtnAction(){
        if self.searchTextField.text?.count == 0{
            self.view.makeToast(message:MMLocalizedString("keyword_search", comment: "请输入搜索车辆"))
        }else{
            self.view.endEditing(true)
            LLKeyValueStore.share()?.put(self.searchTextField.text ?? "", withId: self.searchTextField.text ?? "", intoTable: XTManageCenter.SearchHistoryTable)
            
            self.pageNo = 1
            self.fetchGetCarList(hud: false)
        }
    }
    
    func jumpToLogin(){
        guard let tabbarVC = UIApplication.shared.keyWindow?.rootViewController as? BaseTabbarController else {
            return
        }
        let vc = LoginViewController()
        let loginNavi = BaseNavigationController.init(rootViewController: vc)
        loginNavi.modalPresentationStyle = .fullScreen
        tabbarVC.present(loginNavi, animated: true)
    }
    
}

extension SearchResultViewController: UITextFieldDelegate{
    func textFieldDidBeginEditing(_ textField: UITextField) {
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if string == "\n" {
            if textField.text != "" {
            }
            self.confirmSearchBtnAction()
        }
        return true
    }
}


//分栏
//extension SearchResultViewController: SubfieldTopViewDelegate{
//    func selectDidIndex(index: NSInteger) {
//    }
//}

//筛选
extension SearchResultViewController: FiltrateUserCarViewDelegate{
    func didSelectFilterViewItemAction(itmes: FilterResultParam, index: NSInteger) {
        if index == 2{//
            let vc = ScreenViewController()
            let navi = BaseNavigationController(rootViewController: vc)
            navi.modalPresentationStyle = .fullScreen
            self.present(navi, animated: true, completion: nil)
            
            //选中的筛选条件
            vc.screeningConditionBlock = { [weak self] selectModel in
                self?.selectParam = selectModel
                self?.pageNo = 1
                self?.fetchGetCarList(hud: true)
            }
        }else if index == 0{//售价
            self.selectParam.orderProperty = "0"
            let tempKey = itmes.sort - 1
            self.selectParam.ascOrDesc = "\(tempKey)"
            self.pageNo = 1
            self.fetchGetCarList(hud: true)
            
        }else{//年份
            self.selectParam.orderProperty = "1"
            let tempKey = itmes.sort - 1
            self.selectParam.ascOrDesc = "\(tempKey)"
            self.pageNo = 1
            self.fetchGetCarList(hud: true)
        }
    }
    
}

extension SearchResultViewController: SkeletonCollectionViewDelegate, SkeletonCollectionViewDataSource {
    
    func collectionSkeletonView(_ skeletonView: UICollectionView, cellIdentifierForItemAt indexPath: IndexPath) -> SkeletonView.ReusableCellIdentifier {
        return "SkeletonCollectionCell"
    }
    
    ///SkeletonView 1组
    func numSections(in collectionSkeletonView: UICollectionView) -> Int {
        return 1
    }
    ///SkeletonView 20个item
    func collectionSkeletonView(_ skeletonView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 20
    }
    ///SkeletonView item
    func collectionSkeletonView(_ skeletonView: UICollectionView, skeletonCellForItemAt indexPath: IndexPath) -> UICollectionViewCell? {
        let cell = skeletonView.dequeueReusableCell(withReuseIdentifier: "SkeletonCollectionCell", for: indexPath) as! SkeletonCollectionCell
        cell.clipsToBounds = true
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.dataArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "GoodsCollectionViewCell", for: indexPath) as! GoodsCollectionViewCell
        if self.dataArr.count > indexPath.row{
            let model = self.dataArr[indexPath.row]
            cell.setModel(model: model as! VehicleLisetModel)
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if self.dataArr.count > indexPath.row{
            let model = self.dataArr[indexPath.row] as! VehicleLisetModel
            let vc = VehicleDetailsViewController()
            vc.id = "\(model.id ?? 0)"
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    
}
extension SearchResultViewController: UIScrollViewDelegate{
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offset = scrollView.contentOffset.y
        if offset <= kScreenHeight/2 {
            self.goTopBtn.isHidden = true
        }else{
            self.goTopBtn.isHidden = false
        }
    }
}
